package model

import (
	"context"
	"fmt"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ AccountLogModel = (*customAccountLogModel)(nil)

type (
	// AccountLogModel is an interface to be customized, add more methods here,
	// and implement the added methods in customAccountLogModel.
	AccountLogModel interface {
		accountLogModel
		RowBuilder() squirrel.SelectBuilder
		Truncate(ctx context.Context)
		FindAll(ctx context.Context) ([]*AccountLog, error)
		FindAllEx(userId, Current int64, PageSize int64) (*[]AccountLog, error)
		CountEx(userId int64) (int64, error)
	}

	customAccountLogModel struct {
		*defaultAccountLogModel
	}
)

// NewAccountLogModel returns a model for the database table.
func NewAccountLogModel(conn sqlx.SqlConn, c cache.CacheConf) AccountLogModel {
	return &customAccountLogModel{
		defaultAccountLogModel: newAccountLogModel(conn, c),
	}
}

func (m *defaultAccountLogModel) RowBuilder() squirrel.SelectBuilder {
	return squirrel.Select(accountLogRows).From(m.table)
}

func (m defaultAccountLogModel) Truncate(ctx context.Context) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err == nil {
		var resp []*AccountLog
		err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
		if err == nil {
			for _, r := range resp {
				m.Delete(ctx, r.Id)
			}
			m.ExecNoCacheCtx(ctx, fmt.Sprintf("TRUNCATE %s", m.tableName()))
		}
	}
}

func (m defaultAccountLogModel) FindAll(ctx context.Context) ([]*AccountLog, error) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err != nil {
		return nil, nil
	}

	var resp []*AccountLog
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}

func (m *defaultAccountLogModel) FindAllEx(userId, Current int64, PageSize int64) (*[]AccountLog, error) {

	var query string
	if userId > 0 {
		query = fmt.Sprintf("select * from %s where user_id=? order by create_time desc limit ?,?", m.table)
	} else {
		query = fmt.Sprintf("select * from %s where user_id>? order by create_time desc limit ?,?", m.table)
	}
	var resp []AccountLog
	err := m.CachedConn.QueryRowsNoCache(&resp, query, userId, (Current-1)*PageSize, PageSize)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return &resp, nil
	default:
		return nil, err
	}
}

func (m *defaultAccountLogModel) CountEx(userId int64) (int64, error) {
	var query string
	if userId > 0 {
		query = fmt.Sprintf("select count(*) as count from %s where user_id=?", m.table)
	} else {
		query = fmt.Sprintf("select count(*) as count from %s where user_id>?", m.table)
	}

	var count int64
	err := m.CachedConn.QueryRowNoCache(&count, query, userId)

	switch err {
	case nil:
		return count, nil
	case sqlc.ErrNotFound:
		return 0, nil
	default:
		return 0, err
	}
}
